<?php

namespace app\Api\controller;

use app\common\business\SGoods;
use app\common\business\SGroup as SGroupBus;
use app\common\business\SOrder;
use app\common\business\SOrder as SOrderBus;
use app\common\business\SPartners as SPartnersBus;
use app\common\model\mysql\SGoods as SGoodsModel;
use app\common\lib\Check;
use app\common\model\mysql\SGoodsGroupBuying;
use app\common\model\mysql\SOrderConfigure;
use app\common\model\mysql\SOrderGoods;
use app\common\model\mysql\SOrderRecord;
use app\common\model\mysql\SOrderRefund;
use app\common\model\mysql\SOrderRefundGoods;
use think\facade\Db;

class Order extends AuthBase
{
    // 拼团商品-下单
    public function groupOrder(){
        // 设置默认值
        $allParams = [
            'sharer_uid' => 0,
            'group_buying_id' => 0,
            'mark' => '',
        ];
        // 获取所有请求参数并合并到$allParams中
        $allParams = array_merge($allParams, request()->param());
        if(empty($allParams['goods_group_id'])){
            return show(config("status.error"),"拼团商品id不能为空");
        }
        if($allParams['order_type'] != 1){
            return show(config("status.error"),"订单类型不正确");
        }
        if(empty($allParams['partners_id'])){
            return show(config("status.error"),"合作商id不能为空");
        }
        if(empty($allParams['group_people'])){
            return show(config("status.error"),"拼团阶梯人数不能为空");
        }
        if(empty($allParams['group_price'])){
            return show(config("status.error"),"拼团阶梯价格不能为空");
        }
        if(empty($allParams['total_num'])){
            return show(config("status.error"),"购买数量不能为空");
        }
        if($allParams['group_buying_id']){
            $groupBuyingData = (new SGoodsGroupBuying())->getGoodsGroupBuyingStatus($allParams['group_buying_id']);
            if(empty($groupBuyingData)){
                return show(config("status.error"),"暂无此成团信息");
            }
            if($groupBuyingData['status'] == 1){
                return show(config("status.error"),"此成团人数已满");
            }
            if($groupBuyingData['status'] == 2){
                return show(config("status.error"),"此团时间已到，无法参团");
            }
        }
        $goodsGroupData = (new SGroupBus)->getGoodsGroupById($allParams['goods_group_id']);
        if(empty($goodsGroupData)){
            return show(config("status.error"),"暂无此拼团商品");
        }
        if($goodsGroupData['goods_status'] == '1'){
            return show(config("status.error"),"该拼团商品已下架");
        }
        if($goodsGroupData['del_flag'] == '2'){
            return show(config("status.error"),"该拼团商品已删除");
        }
        if($goodsGroupData['is_restrict'] == 0){
            if($allParams['total_num']>$goodsGroupData['once_pay_count']){
                return show(config("status.error"),"每单限购".$goodsGroupData['once_pay_count']."件");
            }
            $groupWhere[] = ['goods_id','=',$goodsGroupData['goods_id']];
            $groupWhere[] = ['uid','=',$this->memberId];
            $groupWhere[] = ['paid','=',1];
            $goodsOrderNum = (new SOrderGoods())->getOrderGoodsCount($groupWhere);
            if($allParams['total_num']+$goodsOrderNum>$goodsGroupData['pay_count']){
                return show(config("status.error"),"已超过活动总限购".$goodsGroupData['pay_count']."件");
            }
        }
        //根据开始时间和结束时间判断活动状态
        // 获取当前时间
        $now = new \DateTime();
        // 创建 DateTime 对象以进行比较
        $startTime = new \DateTime($goodsGroupData['start_time']);
        $endTime = new \DateTime($goodsGroupData['end_time']);
        // 判断活动状态
        $groupUpdate['goods_id'] = $goodsGroupData['goods_id'];
        if ($startTime > $now) {
            $groupUpdate['action_status'] = '2'; // 活动未开始
            (new SGroupBus())->updateById($goodsGroupData['goods_group_id'],$groupUpdate);
            return show(config("status.error"),"该拼团活动未开始");
        } elseif ($startTime < $now && $endTime > $now) {
            $groupUpdate['action_status'] = '0'; // 活动进行中
            (new SGroupBus())->updateById($goodsGroupData['goods_group_id'],$groupUpdate);
        } else {
            $groupUpdate['action_status'] = '1'; // 活动已结束
            (new SGroupBus())->updateById($goodsGroupData['goods_group_id'],$groupUpdate);
            return show(config("status.error"),"该拼团活动已结束");
        }
        $partnersData = (new SPartnersBus())->getPartnersById($allParams['partners_id']);
        if(empty($partnersData)){
            return show(config("status.error"),"暂无此合作商");
        }
        $goodsData = (new SGoods())->getGoodsById($goodsGroupData['goods_id']);
        if(empty($goodsData)){
            return show(config("status.error"),"暂无此商品");
        }
        if($allParams['total_num']>$goodsData['stock']){
            return show(config("status.error"),"该拼团商品库存量不足");
        }
        $total_price = $pay_price = $allParams['group_price']*$allParams['total_num'];
        $orderData = [
            'order_sn'=>(new Check())->makeOrderNo(),
            'uid'=>$this->memberId,
            'sharer_uid'=>$allParams['sharer_uid'],
            'real_name'=>$partnersData['contact'],
            'user_phone'=>$partnersData['contact_phone'],
            'user_address'=>$partnersData['address'],
            'total_num'=>$allParams['total_num'],
            'total_price'=>$total_price,
            'pay_price'=>$pay_price,
            'platform_commission'=>$goodsGroupData['platform_commission']*$allParams['total_num'],
            'initiator_commission'=>$goodsGroupData['initiator_commission']*$allParams['total_num'],
            'sharer_commission'=>$goodsGroupData['sharer_commission']*$allParams['total_num'],
            'partner_commission'=>$goodsGroupData['partner_commission']*$allParams['total_num'],
            'order_type'=>$allParams['order_type'],
            'create_time'=>date("Y-m-d H:i:s",time()),
            'mark'=>$allParams['mark'],
            'verify_code'=>(new Check())->generateUniqueCode(),
            'activity_type'=>2,
            'status'=>6,
            'order_goods_names'=>$goodsGroupData['group_name'],
        ];
        Db::startTrans();
        try {
            $result = (new SOrderBus())->addOrder($orderData);
            if($result){
                $cart_info = [
                    'goodsData'=>$goodsData,
                    'goodsGroupData'=>$goodsGroupData,
                ];
                $orderGoodsData[] = [
                    'order_id'=>$result,
                    'uid'=>$this->memberId,
                    'goods_id'=>$goodsGroupData['goods_id'],
                    'platform_commission'=>$goodsGroupData['platform_commission'],
                    'initiator_commission'=>$goodsGroupData['initiator_commission'],
                    'sharer_commission'=>$goodsGroupData['sharer_commission'],
                    'partner_commission'=>$goodsGroupData['partner_commission'],
                    'goods_num'=>$allParams['total_num'],
                    'goods_type'=>3,
                    'activity_id'=>$allParams['group_buying_id'],
                    'refund_num'=>$allParams['total_num'],
                    'total_price'=>$allParams['group_price'],
                    'cart_info'=>json_encode($cart_info),
                    'create_time'=>date("Y-m-d H:i:s",time()),
                    'title'=>$goodsGroupData['group_name'],
                    'image'=>$goodsData['main_img_url'],
                ];
                (new SOrderGoods())->insertAllOrderGoods($orderGoodsData);
                //下单成功减库存
                $goodsUpdate['stock'] = $goodsData['stock']-$allParams['total_num'];
                $goodsUpdate['number_ordered'] = $goodsData['number_ordered']+1;
                (new SGoods())->updateById($goodsData['goods_id'],$goodsUpdate);
                //记录订单日志
                (new SOrderRecord())->addOrderRecord($this->memberId,'订单生成',4,$result);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        $payOrder = [
            'order_id'=>$result,
            'goods_name'=>$goodsGroupData['group_name'],
            'order_sn'=>$orderData['order_sn'],
        ];
        return show(config("status.success"),"下单成功",$payOrder);
    }

    // 普通商品-下单
    public function order(){
        // 设置默认值
        $allParams = [
            'sharer_uid' => 0,
            'mark' => '',
        ];
        // 获取所有请求参数并合并到$allParams中
        $allParams = array_merge($allParams, request()->param());
        if(empty($allParams['goods_id'])){
            return show(config("status.error"),"商品id不能为空");
        }
        if($allParams['order_type'] != 1){
            return show(config("status.error"),"订单类型不正确");
        }
        $partnersData = (new SPartnersBus())->getPartnersById($allParams['partners_id']);
        if(empty($partnersData)){
            return show(config("status.error"),"暂无此合作商");
        }
        $goodsData = (new SGoods())->getGoodsById($allParams['goods_id']);
        if(empty($goodsData)){
            return show(config("status.error"),"暂无此商品");
        }
        if($allParams['total_num']>$goodsData['stock']){
            return show(config("status.error"),"该商品库存量不足");
        }
        if($goodsData['status'] == 1){
            return show(config("status.error"),"该商品已下架");
        }
        if($goodsData['del_flag'] == 2){
            return show(config("status.error"),"该商品已删除");
        }
        $total_price = $pay_price = $goodsData['selling_price']*$allParams['total_num'];
        $orderData = [
            'order_sn'=>(new Check())->makeOrderNo(),
            'uid'=>$this->memberId,
            'sharer_uid'=>$allParams['sharer_uid'],
            'real_name'=>$partnersData['contact'],
            'user_phone'=>$partnersData['contact_phone'],
            'user_address'=>$partnersData['address'],
            'total_num'=>$allParams['total_num'],
            'total_price'=>$total_price,
            'pay_price'=>$pay_price,
            'extension_one'=>$goodsData['extension_one']*$allParams['total_num'],
            'extension_two'=>$goodsData['extension_two']*$allParams['total_num'],
            'order_type'=>$allParams['order_type'],
            'create_time'=>date("Y-m-d H:i:s",time()),
            'mark'=>$allParams['mark'],
            'verify_code'=>(new Check())->generateUniqueCode(),
            'activity_type'=>1,
            'status'=>6,
            'order_goods_names'=>$goodsData['goods_name'],
        ];
        Db::startTrans();
        try {
            $result = (new SOrderBus())->addOrder($orderData);
            if($result){
                $cart_info = [
                    'goodsData'=>$goodsData,
                ];
                $orderGoodsData[] = [
                    'order_id'=>$result,
                    'uid'=>$this->memberId,
                    'goods_id'=>$goodsData['goods_id'],
                    'extension_one'=>$goodsData['extension_one'],
                    'extension_two'=>$goodsData['extension_two'],
                    'goods_num'=>$allParams['total_num'],
                    'goods_type'=>0,
                    'activity_id'=>0,
                    'refund_num'=>$allParams['total_num'],
                    'total_price'=>$goodsData['selling_price'],
                    'cart_info'=>json_encode($cart_info),
                    'create_time'=>date("Y-m-d H:i:s",time()),
                    'title'=>$goodsData['goods_name'],
                    'image'=>$goodsData['main_img_url'],
                ];
                (new SOrderGoods())->insertAllOrderGoods($orderGoodsData);
                //下单成功减库存
                $goodsUpdate['stock'] = $goodsData['stock']-$allParams['total_num'];
                $goodsUpdate['number_ordered'] = $goodsData['number_ordered']+1;
                (new SGoods())->updateById($goodsData['goods_id'],$goodsUpdate);
                //记录订单日志
                (new SOrderRecord())->addOrderRecord($this->memberId,'订单生成',4,$result);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        $payOrder = [
            'order_id'=>$result,
            'goods_name'=>$goodsData['goods_name'],
            'order_sn'=>$orderData['order_sn'],
        ];
        return show(config("status.success"),"下单成功",$payOrder);
    }

    // 订单列表
    public function orderList(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $status = $this->request->get("status","");
        //订单状态（0：待发货；1：待收货；2：待评价；3：已完成；4: 拼团中  5：已退款 6:  待付尾款 7:尾款超时未付）
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        $where[] = ["uid","=",$this->memberId];
        $where[] = ["is_del", "=", '0'];
        try {
            $field = "order_id,order_sn,uid,pay_price,order_type,paid,create_time,status,activity_type";
            $orderData = (new SOrderBus())->getNormalOrderData($where,$field,$limit,$page);
            if($orderData['data']){
                $goodsOrderField = "order_goods_id,order_id,is_refund,goods_num,goods_type,activity_id,refund_num,total_price,title,image";
                $SOrderGoodsDb = (new SOrderGoods());
                foreach ($orderData['data'] as $k=>$v){
                    $orderData['data'][$k]['orderGoodsData'] = $SOrderGoodsDb->getOrderGoods($v['order_id'],$goodsOrderField);
                }
            }
        }catch (\Exception $e){
            $orderData = [];
        }
        return show(config("status.success"),"订单列表",$orderData);
    }

    // 取消订单
    public function cancelOrder(){
        $order_id = $this->request->param("order_id", "", "trim");
        if (empty($order_id)) {
            return show(config("status.error"), "参数不能为空");
        }
        $orderData = (new SOrderBus())->getOrderById($order_id,'status');
        if(empty($orderData)){
            return show(config("status.error"), "暂无此订单数据");
        }
        if($orderData['status'] == 7){
            return show(config("status.error"), "此订单已取消");
        }
        $memberId = $this->memberId;
        $orderGoodsData = (new SOrderGoods())->getOrderGoods($order_id, 'goods_id,uid,goods_num,paid');
        if (empty($orderGoodsData)) {
            return show(config("status.error"), "暂无此订单商品数据");
        }
        Db::startTrans();
        try {
            $SGoodsModelDB = (new SGoodsModel());
            foreach ($orderGoodsData as $v) {
                if ($v['paid'] == 1 || $v['uid'] != $memberId) {
                    return show(config("status.error"), "此订单商品已支付或用户不匹配,不能取消");
                }
                $SGoodsModelDB->setIncGoodsData($v['goods_id'],'stock',$v['goods_num']);
                $SGoodsModelDB->setDecGoodsData($v['goods_id'],'number_ordered',1);
            }
            $data['status'] = 7;
            $result = (new SOrderBus())->updateById($order_id, $data);
            // 记录订单日志
            (new SOrderRecord())->addOrderRecord($memberId, '用户取消订单', 4, $order_id);
            Db::commit();
            return show(config("status.success"), "取消订单成功", $result);
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
    }

    // 售后订单
    public function orderRefundList(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $status = $this->request->get("status","");
        //订单状态（0：待发货；1：待收货；2：待评价；3：已完成；4: 拼团中  5：已退款 6:  待付尾款 7:尾款超时未付）
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["a.status", "=", $status];
        }
        $where[] = ["a.uid","=",$this->memberId];
        $where[] = ["a.is_del", "=", '0'];
        try {
            $field = "a.order_refund_id,a.order_refund_sn,a.order_id,a.uid,a.mer_delivery_user,a.mer_delivery_address,a.phone,a.mark,a.refund_type,a.refund_message,a.refund_price,a.refund_num,a.fail_message,a.status,a.create_time,b.order_sn,b.pay_price,b.status as orderStatus,b.real_name";
            $orderRefundData = (new SOrderBus())->getNormalOrderRefundData($where,$field,$limit,$page);
            if ($orderRefundData) {
                $orderRefundData = $this->orderRefundGoodsData($orderRefundData);
                foreach ($orderRefundData['data'] as &$refund) {
                    foreach ($refund['orderGoodsData'] as &$goods) {
                        $goods['image'] = (new Check())->checkUrl($goods['image']);
                    }
                }
            } else {
                $orderRefundData = [];
            }
        }catch (\Exception $e){
            $orderRefundData = [];
        }
        return show(config("status.success"),"售后订单数据列表",$orderRefundData);
    }

    // 添加售后订单商品数据
    private function orderRefundGoodsData($orderData) {
        if (isset($orderData['data']) && !empty($orderData['data'])) {
            foreach ($orderData['data'] as &$order) {
                $orderGoodsData = (new SOrderRefundGoods())->getNormalOrderRefundGoodsList($order['order_refund_id'],'a.*,b.title,b.image,b.total_price,b.goods_num');
                $order['orderGoodsData'] = $orderGoodsData;
            }
        }
        return $orderData;
    }

    // 订单详情
    public function orderDetails(){
        $order_id = $this->request->param("order_id", "", "trim");
        if (empty($order_id)) {
            return show(config("status.error"), "参数不能为空");
        }
        $orderField = "order_id,order_sn,uid,real_name,real_name,user_address,total_num,total_price,pay_price,order_type,paid,pay_time,create_time,status,mark,verify_code,activity_type";
        $orderData = (new SOrderBus())->getOrderById($order_id,$orderField);
        if(empty($orderData)){
            return show(config("status.error"), "暂无此订单数据");
        }
        $memberId = $this->memberId;
        if ($orderData['uid'] != $memberId) {
            return show(config("status.error"), "此订单与用户不匹配");
        }
        $orderGoodsField = "order_goods_id,uid,order_id,goods_id,is_refund,goods_num,goods_num,activity_id,refund_num,total_price,title,image";
        $orderData['orderGoodsData'] = (new SOrderGoods())->getOrderGoods($order_id,$orderGoodsField);
        foreach ($orderData['orderGoodsData'] as &$orderGoods){
            $orderGoods['image'] = (new Check())->checkUrl($orderGoods['image']);
        }
        return show(config("status.success"),"订单详情",$orderData);
    }

    // 售后订单详情
    public function orderRefundDetails(){
        $order_refund_id = $this->request->param("order_refund_id", "", "trim");
        if (empty($order_refund_id)) {
            return show(config("status.error"), "参数不能为空");
        }
        try {
            $field = "a.order_refund_id,a.order_refund_sn,a.order_id,a.uid,a.mer_delivery_user,a.mer_delivery_address,a.phone,a.mark,a.refund_type,a.refund_message,a.refund_price,a.refund_num,a.fail_message,a.status,a.create_time,b.order_sn,b.pay_price,b.status as orderStatus,b.real_name,b.user_phone,b.user_address";
            $orderRefundData = (new SOrderRefund())->getOrderRefundIdData($order_refund_id,$field);
            if ($orderRefundData) {
                $orderGoodsData = (new SOrderRefundGoods())->getNormalOrderRefundGoodsList($order_refund_id,'a.*,b.title,b.image,b.total_price,b.goods_num');
                foreach ($orderGoodsData as &$goods){
                    $goods['image'] = (new Check())->checkUrl($goods['image']);
                }
                $orderRefundData['orderGoodsData'] = $orderGoodsData;
            } else {
                $orderRefundData = [];
            }
        }catch (\Exception $e){
            $orderRefundData = [];
        }
        return show(config("status.success"),"售后订单详情",$orderRefundData);
    }

    // 订单配置
    public function getOrderConfigure(){
        $merId = $this->request->param("merId","0","trim");
        try {
            $orderConfigureData = (new SOrderConfigure())->getOrderConfigure($merId);
            $orderConfigureData['consignee_reason'] = explode("\n", $orderConfigureData['consignee_reason']);
        }catch (\Exception $e){
            $orderConfigureData = [];
        }
        return show(config("status.success"),"订单配置",$orderConfigureData);
    }

    // 订单申请退款
    public function applicationOrderRefund(){
        $order_id = $this->request->param("order_id", "", "trim");
        if (empty($order_id)) {
            return show(config("status.error"), "订单id不能为空");
        }
        $refund_message = $this->request->param("refund_message", "", "trim");
        if (empty($refund_message)) {
            return show(config("status.error"), "退款原因不能为空");
        }
        $refund_num = $this->request->param("refund_num", "", "trim");
        if (empty($refund_num)) {
            return show(config("status.error"), "退款数不能为空");
        }
        $mark = $this->request->param("mark", "", "trim");
        $orderRefundData = (new SOrderBus())->getRefundOrderById($order_id);
        if($orderRefundData){
            if($orderRefundData['status'] != -1){
                return show(config("status.error"), "此订单已申请售后，不能重复申请");
            }
        }
        $orderData = (new SOrderBus())->getOrderById($order_id);
        $memberId = $this->memberId;
        if ($orderData['uid'] != $memberId) {
            return show(config("status.error"), "此订单与用户不匹配");
        }
        $orderConfigureData = (new SOrderConfigure())->getOrderConfigure($orderData['mer_id']);
        $refundOrderData = [
            'order_refund_sn'=>(new Check())->makeRefundOrderNo(),
            'order_id'=>$order_id,
            'uid'=>$this->memberId,
            'mer_id'=>$orderData['mer_id'],
            'extension_one'=>$orderData['extension_one'],
            'extension_two'=>$orderData['extension_two'],
            'mer_delivery_user'=>$orderConfigureData['consignee_name'],
            'mer_delivery_address'=>$orderConfigureData['consignee_address'],
            'phone'=>$orderConfigureData['consignee_phone'],
            'mark'=>$mark,
            'refund_type'=>1,
            'refund_message'=>$refund_message,
            'refund_price'=>$orderData['pay_price'],
            'refund_num'=>$refund_num,
            'status_time'=>date("Y-m-d H:i:s",time()),
            'create_time'=>date("Y-m-d H:i:s",time()),
            'platform_commission'=>$orderData['platform_commission'],
            'initiator_commission'=>$orderData['initiator_commission'],
            'sharer_commission'=>$orderData['sharer_commission'],
            'partner_commission'=>$orderData['partner_commission'],
        ];
        Db::startTrans();
        try {
            $result = (new SOrderBus())->addRefundOrder($refundOrderData);
            if($result){
                $SOrderGoodsDB = (new SOrderGoods());
                $orderGoodsData = $SOrderGoodsDB->getOrderGoods($order_id);
                $refundOrderGoodsData = [];
                foreach ($orderGoodsData as $k=>$v){
                    $refundOrderGoodsData[$k] = [
                        'order_refund_id'=>$result,
                        'order_goods_id'=>$v['order_goods_id'],
                        'refund_price'=>$v['total_price']*$v['goods_num'],
                        'refund_num'=>$v['refund_num'],
                        'create_time'=>date("Y-m-d H:i:s",time()),
                    ];
                    $updateOrderGoods['is_refund'] = 1;
                    $updateOrderGoods['refund_num'] = 0;
                    $SOrderGoodsDB->saveOrderGoodsbyId($v['order_goods_id'],$updateOrderGoods);
                }
                (new SOrderRefundGoods())->insertAllOrderRefundGoods($refundOrderGoodsData);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        $rufundOrder = [
            'order_refund_id'=>$result,
            'order_refund_sn'=>$refundOrderData['order_refund_sn'],
        ];
        return show(config("status.success"),"申请退款成功",$rufundOrder);
    }
}
